package com.example.util;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.concurrent.ConcurrentHashMap;

/*这个是创建WebSocket处理器*/
public class MyWebSocketHandler extends TextWebSocketHandler{
    //订单ID=>WebSocketSession 映射
    public static final ConcurrentHashMap<String,WebSocketSession> orderSessionMap = new ConcurrentHashMap<>();


    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //从query中获取orderId
        String query = session.getUri().getQuery();
        String orderId=null;
        if(query !=null && query.startsWith("orderId=")){
            orderId = query.split("=")[1];
        }
        if (orderId !=null){
            orderSessionMap.put(orderId,session);
            System.out.println("orderId:"+orderId+"已连接");
        }else{
            System.out.println("未提供orderId,关闭连接");
            session.close();
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String clientMsg = message.getPayload();
        System.out.println("收到信息"+clientMsg);
        session.sendMessage(new TextMessage("收到成功连接"));
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        orderSessionMap.values().removeIf(sess -> sess.getId().equals(session.getId()));
    }
}
